package com.sys.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sys.entity.TxtExport;
import com.sys.service.TxtExportService;
import com.sys.utils.TxtExportUtils;
import com.bhudy.exception.SysException;
import com.bhudy.exception.SysExceptionCode;
import com.bhudy.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author bhudy
 * @Description 文件读写，代码生成Controller
 * @Date 2019-10-30 23:09:37
 */
@RestController
public class TxtExportController {

    @Value("${bhudy.packagePath}")
    private String packagePath;
    @Autowired
    private TxtExportService baseService;
    @Value("${spring.datasource.driverClassName}")
    private String driverClassName = "org.postgresql.Driver";


    @GetMapping(value = "/api/v1/sysTables")
    public ResponseResult showTables() {
        String sql;
        if (driverClassName.toLowerCase().indexOf("mysql") != -1) {
            sql = "show tables";
        } else if (driverClassName.toLowerCase().indexOf("postgresql") != -1) {
            sql = "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'";
        } else if (driverClassName.toLowerCase().indexOf("sqlserver") != -1) {
            throw new SysException(SysExceptionCode.CODE_40001);
        } else if (driverClassName.toLowerCase().indexOf("oracle") != -1) {
            throw new SysException(SysExceptionCode.CODE_40001);
        } else {
            sql = "show tables";
        }

        List<Map<String, Object>> tableList = baseService.findMapList(sql);

        if (tableList == null || tableList.size() == 0) return null;

        List<String> tabStrList = new ArrayList<>();
        for (Map<String, Object> tableMap : tableList) {
            for (Map.Entry<String, Object> entry : tableMap.entrySet()) {
                tabStrList.add(entry.getValue().toString());
            }
        }

        return ResponseResult.printMapJson(0, tabStrList);
    }

    @GetMapping(value = "/api/v1/sysColumns")
    public ResponseResult getColumns(String tableName) {
        String sql;
        List<String> argList = new ArrayList<>();
        if (driverClassName.toLowerCase().indexOf("mysql") != -1) {
            sql = "show full columns from " + tableName;
        } else if (driverClassName.toLowerCase().indexOf("postgresql") != -1) {
            sql = "SELECT a.attname as \"Field\", format_type(a.atttypid,a.atttypmod) as \"Type\", col_description(a.attrelid,a.attnum) as \"Comment\", '' as \"Key\"\n" +
                    "FROM pg_class as c,pg_attribute as a where c.relname = ? and a.attrelid = c.oid and a.attnum > 0";
            argList.add(tableName);
        } else if (driverClassName.toLowerCase().indexOf("sqlserver") != -1) {
            throw new SysException(SysExceptionCode.CODE_40001);
        } else if (driverClassName.toLowerCase().indexOf("oracle") != -1) {
            throw new SysException(SysExceptionCode.CODE_40001);
        } else {
            sql = "show full columns from " + tableName;
        }
        return ResponseResult.printMapJson(0, baseService.findMapList(sql, argList.toArray()));
    }

    @PostMapping(value = "/api/v1/sysCreate")
    public ResponseResult create(@RequestBody String json) {
        try {
            System.out.println(json);

            Map<String, Object> dataMap = JSONObject.parseObject(json, Map.class);
            if (dataMap.containsKey("select") && !(dataMap.get("select") instanceof Boolean)) {
                dataMap.put("select", dataMap.containsKey("select") && dataMap.get("select") instanceof String && ((String) dataMap.get("select")).equals("on"));
                dataMap.put("insert", dataMap.containsKey("insert") && dataMap.get("insert") instanceof String && ((String) dataMap.get("insert")).equals("on"));
                dataMap.put("update", dataMap.containsKey("update") && dataMap.get("update") instanceof String && ((String) dataMap.get("update")).equals("on"));
                dataMap.put("delete", dataMap.containsKey("delete") && dataMap.get("delete") instanceof String && ((String) dataMap.get("delete")).equals("on"));
            }

            TxtExport txtExport = JSONObject.parseObject(JSONObject.toJSONString(dataMap), TxtExport.class);
            txtExport.setPackagePath(packagePath);

            TxtExportUtils.createMapper(txtExport);
            TxtExportUtils.createDao(txtExport);
            TxtExportUtils.createEntity(txtExport);
            TxtExportUtils.createService(txtExport);
            TxtExportUtils.createServiceImpl(txtExport);
            TxtExportUtils.createController(txtExport);
            TxtExportUtils.createTemplate(txtExport);
        } catch (Exception e) {
            throw new SysException(SysExceptionCode.CODE_40005, e.getMessage());
        }
        return ResponseResult.printMapJson(0, null);
    }
}
